package com.hetang.maijiayun.adaptertools.service.impl;

import com.hetang.maijiayun.adaptertools.config.B2cInterfaceConfig;
import com.hetang.maijiayun.adaptertools.config.MessageConfig;
import com.hetang.maijiayun.adaptertools.controller.vo.request.SyncRequest;
import com.hetang.maijiayun.adaptertools.controller.vo.response.MessageResponse;
import com.hetang.maijiayun.adaptertools.controller.vo.response.PlatformLostShops;
import com.hetang.maijiayun.adaptertools.controller.vo.response.Response;
import com.hetang.maijiayun.api.eshop.EShop;
import com.hetang.maijiayun.api.eshop.EShopAuthorize;
import com.hetang.maijiayun.api.eshop.IEShopAuthorizeService;
import com.hetang.maijiayun.api.eshop.IEShopService;
import com.hetang.maijiayun.api.order.IOrderService;
import com.hetang.maijiayun.api.order.Order;
import com.hetang.maijiayun.api.privilege.ITenantryService;
import com.hetang.maijiayun.api.privilege.Tenantry;
import com.hetang.maijiayun.api.util.APIException;
import com.hetang.maijiayun.adaptertools.commons.group.GroupInterface;
import com.hetang.maijiayun.adaptertools.commons.group.GroupObject;
import com.hetang.maijiayun.adaptertools.controller.vo.request.DetectorRequest;
import com.hetang.maijiayun.adaptertools.controller.vo.response.ShopLostOrder;
import com.hetang.maijiayun.adaptertools.service.IDetectorService;
import com.hetang.maijiayun.api.util.PageResultSet;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 10/26/2015.
 * 默认实现
 */
@Service("detectorService")
public class DetectorServiceImpl implements IDetectorService {
    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(DetectorServiceImpl.class);

    /**
     * 订单服务service
     */
    @Autowired
    private IOrderService iorderService;
    /**
     * 门店服务service
     */
    @Autowired
    private IEShopService iEShopService;
    /**
     * 租户服务service
     */
    @Autowired
    private ITenantryService itenantryService;
    /**
     * 门店授权服务service
     */
    @Autowired
    private IEShopAuthorizeService iEShopAuthorizeService;
    /**
     * 注入配置及平台服务
     */
    @Autowired
    private B2cInterfaceConfig b2cInterfaceConfig;

    /**
     * 根据平台获取漏单的门店
     *
     * @param request
     * @return
     */
    @Override
    public Response<PlatformLostShops> findLostShops(DetectorRequest request) throws Exception {
        Response<PlatformLostShops> response = new Response<PlatformLostShops>();
        MessageResponse message = new MessageResponse(MessageConfig.SUCCESS_CODE, MessageConfig.SUCCESS_CONTEXT);
        if (request == null || StringUtils.isBlank(request.getPlatform())) {
            logger.error("request time {}, request param is null!!", System.currentTimeMillis());
            message.setMessageCode(MessageConfig.PARAM_FAIL_CODE);
            message.setMessageContext(MessageConfig.PARAM_FAIL_CONTEXT);
            response.setResponse(message);
            return response;
        }
        // 得到门店
        PageResultSet<EShop> eShops = null;

        // 得到平台下所有门店
        if (StringUtils.isNotBlank(request.getPlatform())) {
            //
            eShops = iEShopService.getAllByB2cIdentifier(b2cInterfaceConfig.getB2cInterface().get(request.getPlatform()), false, request.getPageNo(), request.getPageSize(), true);//.getAllByB2cIdentifier(request.getPlatform(), true);
        } else {
            message.setMessageCode(MessageConfig.PARAM_FAIL_CODE);
            message.setMessageContext(MessageConfig.PARAM_FAIL_CONTEXT);
            response.setResponse(message);
            return response;
        }
        // 转换对象
        PlatformLostShops lostShops = this.convertPlatformBean(eShops, request);
        if (CollectionUtils.isNotEmpty(eShops.getPage()) && null != lostShops) {
            // 得到授权信息
            List<EShopAuthorize> eShopAuthorizeList = this.getEShopsAuthors(eShops.getPage());
            // 得到丢失单据的门店
            List<ShopLostOrder> shopLostOrder = this.findLostOrderShops(eShopAuthorizeList, request);
            if (CollectionUtils.isNotEmpty(shopLostOrder)) {
                message.setMessageCode(MessageConfig.LOST_FAIL_CODE);
                message.setMessageContext(MessageConfig.LOST_FAIL_CONTEXT);
            }
            response.setResponse(message);
            lostShops.setShopList(shopLostOrder);
            response.setData(lostShops);
        }
        response.setResponse(message);
        return response;
    }

    @Override
    public MessageResponse syncOrders(SyncRequest request) throws Exception {
        MessageResponse response = new MessageResponse(MessageConfig.SUCCESS_CODE, MessageConfig.SYNC_SUCCESS_CONTEXT);
        if (null == request || null == request.getEndTime() || null == request.getStartTime() || StringUtils.isBlank(request.getPlatform())) {
            response.setMessageCode(MessageConfig.PARAM_FAIL_CODE);
            response.setMessageContext(MessageConfig.PARAM_FAIL_CONTEXT);
            return response;
        }
        List<EShop> eShops = iEShopService.getAllByB2cIdentifier(b2cInterfaceConfig.getB2cInterface().get(request.getPlatform()), false);
        if (CollectionUtils.isEmpty(eShops)) {
            return response;
        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        Date startTime = sdf.parse(request.getStartTime().toString());
//        Date endTime = sdf.parse(request.getEndTime().toString());
        for (Iterator<EShop> iterator = eShops.iterator(); iterator.hasNext(); ) {
            EShop eShop = iterator.next();
            iEShopService.requestEshopOrderSyncByB2cCodeAndTime(eShop.getTenantryId(), eShop.getB2cCode(), request.getStartTime(), request.getEndTime());
        }
        return response;
    }


    /**
     * 获取门店丢失的订单
     *
     * @param eShopAuthorizeList
     * @return
     */
    private List<ShopLostOrder> findLostOrderShops(List<EShopAuthorize> eShopAuthorizeList, DetectorRequest request) throws Exception {
        if (CollectionUtils.isEmpty(eShopAuthorizeList)) {
            return null;
        }
        List<ShopLostOrder> shopLostOrderList = new ArrayList<ShopLostOrder>();

        for (Iterator<EShopAuthorize> iterator = eShopAuthorizeList.iterator(); iterator.hasNext(); ) {

            //  根据不同的平台调用不同的接口
            EShopAuthorize authorize = iterator.next();

            String b2cIdentifier = authorize.geteShopCode().split("\\|")[0];
            if (!b2cIdentifier.equals(b2cInterfaceConfig.getB2cInterface().get(request.getPlatform()))) {
                continue;
            }
            //  得到门店丢失订单
            List<String> orders = this.findShopLostOrders(authorize, b2cIdentifier, request);
            if (CollectionUtils.isEmpty(orders)) {
                continue;
            }
            //  进行转换
            ShopLostOrder order = this.convertBean(authorize, request);
            order.setOrderList(orders);
            shopLostOrderList.add(order);
        }
        return shopLostOrderList;
    }

    /**
     * 得到门店的漏单详细数据
     *
     * @param authorize
     * @param b2cIdentifier
     * @param request
     * @return
     * @throws Exception
     */
    private List<String> findShopLostOrders(EShopAuthorize authorize, String b2cIdentifier, DetectorRequest request) throws Exception {
        //  根据不同的平台调用不同的接口
        List<String> platformOrder = this.findPlatformOrder(authorize.getAuthorizesMap(), b2cIdentifier, request);
        if (CollectionUtils.isEmpty(platformOrder)) {
            return null;
        }
        List<String> orderList = new ArrayList<String>();
        for (Iterator<String> iterator = platformOrder.iterator(); iterator.hasNext(); ) {
            orderList.add(b2cInterfaceConfig.getB2cInterface().get(request.getPlatform()) + "|" + iterator.next());
        }
        List<Order> orders = iorderService.getOrdersByShopId(authorize.getTenantryId(), authorize.geteShopCode(), orderList);
        if (CollectionUtils.isEmpty(orders)) {
            return platformOrder;
        }
        //  eshop按照tenantryId分组
        Map<String, List<Order>> orderMap = GroupObject.INSTANCE.group(orders, new GroupInterface<String>() {
            public String groupby(Object obj) {
                Order detail = (Order) obj;
                return detail.getB2cCode().split("\\|")[1]; // 分组依据b2c_code
            }
        });
        List<String> result = new ArrayList<String>();
        for (Iterator<String> iterator = platformOrder.iterator(); iterator.hasNext(); ) {
            String orderId = iterator.next();
            if (CollectionUtils.isEmpty(orderMap.get(orderId))) {
                result.add(orderId);
            }
        }
        return result;
    }

    /**
     * 根据门店得到授权信息
     *
     * @param eShops
     * @return
     * @throws APIException
     */
    private List<EShopAuthorize> getEShopsAuthors(List<EShop> eShops) throws APIException {
        if (CollectionUtils.isEmpty(eShops)) {
            return null;
        }

        List<EShopAuthorize> eShopAuthorize = new ArrayList<EShopAuthorize>();
        //  eshop按照tenantryId分组
        Map<Long, List<EShop>> eShopMap = GroupObject.INSTANCE.group(eShops, new GroupInterface<Long>() {
            public Long groupby(Object obj) {
                EShop detail = (EShop) obj;
                return detail.getTenantryId(); // 分组依据为商家编码
            }
        });
        List<EShopAuthorize> authorizeList = null;

        Set<Map.Entry<Long, List<EShop>>> entry = eShopMap.entrySet();

        for (Iterator<Map.Entry<Long, List<EShop>>> ite = entry.iterator(); ite.hasNext(); ) {

            Map.Entry<Long, List<EShop>> kv = ite.next();
            EShopAuthorize[] eShopAuthorizes = iEShopAuthorizeService.getList(kv.getKey(), null);

            if (!ArrayUtils.isEmpty(eShopAuthorizes)) {
                authorizeList = Arrays.asList(eShopAuthorizes);
                eShopAuthorize.addAll(authorizeList);
            }
        }
        return eShopAuthorize;
    }

    /**
     * 得到当前门店下在第三方平台的订单
     *
     * @param authorizesMap
     * @param b2cIdentifier
     * @param request
     * @return
     * @throws Exception
     * @todo 暂时先这样处理
     */
    private List<String> findPlatformOrder(Map<String, String> authorizesMap, String b2cIdentifier, DetectorRequest request) throws Exception {
        // taobao
        List<String> response = b2cInterfaceConfig.getB2cService().get(request.getPlatform()).requestOrders(authorizesMap, request);

        return response;
    }

    /**
     * 转换bean
     *
     * @param authorize
     * @param request
     * @return
     */
    private ShopLostOrder convertBean(EShopAuthorize authorize, DetectorRequest request) throws APIException {
        ShopLostOrder order = new ShopLostOrder();
        order.setShopName(authorize.geteShopName());
        order.setShopId(authorize.geteShopCode());
        Tenantry tenantry = itenantryService.get(authorize.getTenantryId());
        order.setTenantryName(tenantry.getCompanyName());
        return order;
    }

    /**
     * 转换bean
     *
     * @param eShops
     * @param request
     * @return
     */
    private PlatformLostShops convertPlatformBean(PageResultSet<EShop> eShops, DetectorRequest request) {
        if (null == eShops || null == request) {
            return null;
        }
        PlatformLostShops lostShops = new PlatformLostShops();
        lostShops.setPlatform(request.getPlatform());
        lostShops.setPageNo(request.getPageNo());
        lostShops.setStartTime(request.getStartTime().toString());
        lostShops.setEndTime(request.getEndTime().toString());
        lostShops.setIsNext(eShops.getIsHasNext());
        return lostShops;
    }
}
